<script setup lang="ts">
// 登录
import {onMounted, ref} from 'vue'
import {loginApi, getCaptchaApi} from '@/assets/api/login'
import {useCookies} from "vue3-cookies"
import {ElMessage, type FormInstance} from "element-plus"
import router from "@/router"
import {encodeStr} from "@/components/baseTs/encrypt"
import type {AxiosResponseHeaders} from "axios";

const {cookies} = useCookies()

// 表单参数
const form = ref<{
  username: string,
  password: string,
  captchaCode: string,
  captchaKey: string
}>({
  username: '',
  password: '',
  captchaCode: '',
  captchaKey: ''
})

// 表单验证
const formRef = ref()
const rules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'}
  ],
  captchaCode: [
    {required: true, message: '请输入验证码', trigger: 'blur'}
  ]
}

// 验证码地址
const captchaUrl = ref('')

// 登录
const submitLoading = ref(false)
const onSubmit = async (formEl: FormInstance) => {
  if (!formEl) return false
  await formEl.validate((valid: boolean) => {
    if (valid) {
      let password = encodeStr(form.value.password)
      if (password)
        form.value.password = password
      submitLoading.value = true
      loginApi(form.value).then(res => {
        submitLoading.value = false
        if (res.data.code === 200) {
          ElMessage.success({message: '登录成功', showClose: true})
          cookies.set('userToken', res.data.data.token)
          cookies.set('name', res.data.data.name)
          router.push('/index')
        } else {
          form.value.password = '' // 清空密码
          ElMessage.error({message: res.data.data, showClose: true})
        }
      })
    }
  })
}

// 刷新验证码
const resetCaptcha = () => {
  getCaptchaApi().then((res) => {
    // 如果返回状态码为401，则清除token
    if (res.data.type === "application/json") {
      cookies.remove('userToken')
      cookies.remove('name')
      return
    }
    // 创建一个 URL 对象
    captchaUrl.value = URL.createObjectURL(res.data)
    form.value.captchaKey = (res.headers as AxiosResponseHeaders).get('captchaKey') + ''
  })
}

onMounted(() => {
  resetCaptcha()
})
</script>

<template>
  <div class="login-container">
    <el-row style="height: 20vh;">
      <el-col span="24">

      </el-col>
    </el-row>
    <el-row style="height: 50vh;">
      <el-col class="login-content" :span="5">
        <div  class="login-header">
          投资数据管理平台
        </div>
        <div class="login-div">
          <div class="login-title">
            <h2>用&nbsp;户&nbsp;登&nbsp;录</h2>
          </div>
          <el-form v-loading="submitLoading" :model="form" :rules="rules" ref="formRef" label-width="auto">
            <el-form-item label="" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名"/>
            </el-form-item>
            <el-form-item label="" prop="password">
              <el-input type="password" v-model="form.password" placeholder="请输入密码" show-password/>
            </el-form-item>
            <el-form-item label="" prop="captchaCode">
              <el-input class="verification-input" v-model="form.captchaCode" placeholder="请输入验证码"/>
              <el-image style="margin-left: 5%; width: 35%;" @click="resetCaptcha" :src="captchaUrl"
                        alt="无法获取验证码"/>
            </el-form-item>
            <el-form-item>
              <el-button class="login-btn" type="primary" @click="onSubmit(formRef)">登录</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
    <el-row  style="height: 30vh;">
      <el-col span="24">

      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.login-container {
  background-image: url("@/assets/img/login.png");
  background-size: cover;
}

.login-content {
  margin-left: 9%;
  text-align: center;
}

.login-header {
  color: #ffffff;
  font-size: 2rem;
  font-weight: bold;
  padding-bottom: 10%;
  text-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}

.login-div {
  background-color: rgb(255, 255, 255);
  padding: 10%;
  border-radius: 5%;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}

.login-title {
  text-align: center;
  color: #000000;
  padding-bottom: 10%;
}

.verification-input {
  width: 50%;
  display: inline-block;
}

.login-btn {
  margin-top: 5%;
  height: 100%;
  width: 100%;
}
</style>
